package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

//GlobalFilter是过滤器接口
// 加上这个注解后，Spring 会在启动时扫描配置文件中符合前缀要求的配置项，并将它们的值注入到 AuthProperties 类的实例中。
@EnableConfigurationProperties(AuthProperties.class)
@Component
public class AuthGlobalFilter implements GlobalFilter {

//filter:过滤器的核心方法，所有经过网关的请求都会触发该方法
//通过它可以获取请求对象（request）和响应对象（response）
//调用chain.filter(exchange)可以将请求传递给下一个过滤器

    @Autowired
    private AuthProperties authProperties;
    //可以对路径判断,/users/login/符合/user/**,所以返回true
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private JwtTool jwtTool;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、获取request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2、获取请求路径
        String path = request.getURI().getPath();
        //获取yaml配置中的排除路径列表,对stream流每个元素处理,判断跟获取的路径相等不
        boolean bo = authProperties.getExcludePaths()
                .stream()
                .anyMatch(url -> antPathMatcher.match(url,path));

        //3、判断路径是否不需要对令牌进行校验。如果不需要，直接放行
        if (bo){
            return chain.filter(exchange);
        }
        //4、需要拦截校验，获取请求头中的令牌,此方法会认为有authorization=1,2,c多个
        String token = request.getHeaders().getFirst("authorization");

        //5对令牌校验
        //token为空的话就进行拦截
        Long userId = null;
        try {
           userId= jwtTool.parseToken(token);
        } catch (Exception e) {
            //6.校验不通过,执行拦截操作
            response.setStatusCode(HttpStatus.UNAUTHORIZED); //响应状态码
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON); //表明响应体是 JSON 格式的数据
            return response.writeWith(Mono.just(response.bufferFactory().wrap("{\"msg\":\"请先登录！\"}".getBytes(StandardCharsets.UTF_8))));
        }

        //7.解析令牌,获取用户ID,把用户ID放到请求头中
        //将用户ID变为字符串
        String userInfo = userId.toString();
        //对请求体操作,将信息变为键值对
        request.mutate().headers(new Consumer<HttpHeaders>() {
            @Override
            public void accept(HttpHeaders httpHeaders) {
                httpHeaders.set("user-info",userInfo);
            }
        });


        //5、放行33
        return chain.filter(exchange);



    }
}
